package com.sgcc.nfc.lock.presentation.main

import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.Menu
import android.view.MenuItem
import androidx.appcompat.app.AppCompatActivity
import androidx.navigation.NavController
import androidx.navigation.fragment.NavHostFragment
import androidx.navigation.ui.AppBarConfiguration
import androidx.navigation.ui.setupActionBarWithNavController
import androidx.navigation.ui.setupWithNavController
import com.google.android.material.bottomnavigation.BottomNavigationView
import com.sgcc.nfc.lock.R
import com.sgcc.nfc.lock.core.storage.TokenManager
import com.sgcc.nfc.lock.presentation.auth.LoginActivity
import com.sgcc.nfc.lock.domain.usecase.GetProfileUseCase
import com.sgcc.nfc.lock.core.network.NetworkResult
import dagger.hilt.android.AndroidEntryPoint
import androidx.lifecycle.lifecycleScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.flow.first
import javax.inject.Inject

@AndroidEntryPoint
class MainActivity : AppCompatActivity() {
    
    companion object {
        private const val TAG = "MainActivity"
    }
    
    @Inject
    lateinit var tokenManager: TokenManager
    
    @Inject
    lateinit var getProfileUseCase: GetProfileUseCase
    
    private lateinit var navController: NavController
    private var fromLogin = false
    
    override fun onCreate(savedInstanceState: Bundle?) {
        System.out.println("=== MainActivity onCreate: 开始 ===")
        Log.d(TAG, "onCreate: 开始")
        super.onCreate(savedInstanceState)
        
        // 检查是否来自登录页面
        fromLogin = intent.getBooleanExtra("FROM_LOGIN", false)
        Log.d(TAG, "onCreate: fromLogin = $fromLogin")
        
        try {
            Log.d(TAG, "onCreate: 设置布局")
            setContentView(R.layout.activity_main)
            
            Log.d(TAG, "onCreate: 设置工具栏")
            // 设置工具栏
            setSupportActionBar(findViewById(R.id.toolbar))
            
            Log.d(TAG, "onCreate: 设置Navigation")
            // 设置Navigation
            setupNavigation()
            
            Log.d(TAG, "onCreate: 完成")
        } catch (e: Exception) {
            Log.e(TAG, "onCreate: 初始化失败", e)
            // 如果设置失败，跳转到登录页面
            navigateToLogin("初始化失败: ${e.message}")
        }
    }
    
    private fun setupNavigation() {
        Log.d(TAG, "setupNavigation: 开始")
        try {
            Log.d(TAG, "setupNavigation: 查找NavHostFragment")
            val navHostFragment = supportFragmentManager
                .findFragmentById(R.id.nav_host_fragment) as NavHostFragment
            navController = navHostFragment.navController
            Log.d(TAG, "setupNavigation: NavController获取成功")
            
            Log.d(TAG, "setupNavigation: 设置底部导航")
            val bottomNav = findViewById<BottomNavigationView>(R.id.bottom_navigation)
            bottomNav.setupWithNavController(navController)
            
            Log.d(TAG, "setupNavigation: 设置AppBar配置")
            val appBarConfiguration = AppBarConfiguration(
                setOf(
                    R.id.homeFragment,
                    R.id.locksFragment,
                    R.id.roomsFragment,
                    R.id.mapFragment,
                    R.id.profileFragment
                )
            )
            setupActionBarWithNavController(navController, appBarConfiguration)
            
            Log.d(TAG, "setupNavigation: 完成")
        } catch (e: Exception) {
            Log.e(TAG, "setupNavigation: 失败", e)
            navigateToLogin("Navigation设置失败: ${e.message}")
        }
    }
    
    override fun onResume() {
        Log.d(TAG, "onResume: 开始")
        super.onResume()
        
        // 检查token有效性
        if (!fromLogin) {
            Log.d(TAG, "onResume: 不是从登录页面来的，检查token有效性")
            checkTokenAndNavigate()
        } else {
            Log.d(TAG, "onResume: 从登录页面来的，跳过token检查")
        }
        Log.d(TAG, "onResume: 完成")
    }
    
    private fun checkTokenAndNavigate() {
        lifecycleScope.launch {
            try {
                val token = tokenManager.accessToken.first()
                Log.d(TAG, "checkTokenAndNavigate: 获取到token = ${if (token.isNullOrEmpty()) "空" else "有值"}")
                
                if (token.isNullOrEmpty()) {
                    Log.d(TAG, "checkTokenAndNavigate: token为空，跳转到登录页面")
                    navigateToLogin("请先登录")
                } else {
                    // 使用GetProfileUseCase验证token有效性
                    Log.d(TAG, "checkTokenAndNavigate: 验证token有效性")
                    when (val result = getProfileUseCase()) {
                        is NetworkResult.Success -> {
                            Log.d(TAG, "checkTokenAndNavigate: token有效，用户信息: ${result.data?.username}")
                            // Token有效，继续使用应用
                        }
                        is NetworkResult.Error -> {
                            Log.d(TAG, "checkTokenAndNavigate: token无效或已过期: ${result.message}")
                            navigateToLogin("登录已过期，请重新登录")
                        }
                        is NetworkResult.Loading -> {
                            // 忽略加载状态
                            Log.d(TAG, "checkTokenAndNavigate: 正在验证token...")
                        }
                    }
                }
            } catch (e: Exception) {
                Log.e(TAG, "checkTokenAndNavigate: 检查token失败", e)
                navigateToLogin("认证检查失败，请重新登录")
            }
        }
    }
    
    private fun navigateToLogin(reason: String = "") {
        val intent = Intent(this, LoginActivity::class.java)
        if (reason.isNotEmpty()) {
            intent.putExtra("ERROR_MESSAGE", reason)
        }
        startActivity(intent)
        finish()
    }
    
    override fun onCreateOptionsMenu(menu: Menu?): Boolean {
        menuInflater.inflate(R.menu.main_toolbar_menu, menu)
        return true
    }
    
    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        return when (item.itemId) {
            R.id.action_map -> {
                // 跳转到地图页面
                try {
                    navController.navigate(R.id.mapFragment)
                } catch (e: Exception) {
                    // 如果导航失败，忽略错误
                }
                true
            }
            else -> super.onOptionsItemSelected(item)
        }
    }
    
    override fun onSupportNavigateUp(): Boolean {
        return navController.navigateUp() || super.onSupportNavigateUp()
    }
}

